package org.example.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.example.annotation.AuthCheck;
import org.example.common.BaseResponse;
import org.example.common.ResultUtils;
import org.example.constant.UserConstant;
import org.example.domain.User;
import org.example.exception.BusinessException;
import org.example.exception.ErrorCode;
import org.example.exception.ThrowUtils;
import org.example.request.*;
import org.example.service.UserService;
import org.example.vo.LoginUserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(ObjectUtils.isEmpty(userRegisterRequest), ErrorCode.PARAMS_ERROR);
        String userAccount = userRegisterRequest.getAccount();
        String userPassword = userRegisterRequest.getPassword();
        long result = userService.userRegister(userAccount, userPassword);
        return ResultUtils.success(result);
    }
    /**
    * 验证码生成
    */

    @GetMapping("/getCode")
    public void getCode(String account,HttpServletResponse response) {
        // 生成唯一的验证码Key，使用UUID
        String captchaKey = "captcha:" + account;

        // 创建验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36, 4, 5);

        // 将验证码存储到Redis中，使用唯一的Key
        redisTemplate.opsForValue().set(captchaKey, lineCaptcha.getCode(), 1, TimeUnit.MINUTES); // 设置验证码有效期为1分钟

        // 将验证码Key作为响应头返回给客户端，客户端需要保存这个Key用于后续验证
        response.setHeader("captchaKey", captchaKey);

        try (ServletOutputStream outputStream = response.getOutputStream()) {
            lineCaptcha.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        System.out.println("www"+request.getSession());
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        LoginUserVO loginUserVO = userService.userLogin(userLoginRequest.getAccount(), userLoginRequest.getPassword(), request);

        // 确保以下方式设置 session
        User user = new User();
        BeanUtils.copyProperties(loginUserVO, user);
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return ResultUtils.success(loginUserVO);
    }
    /**
     * 获取当前登录用户
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        System.out.println("getLoginUser"+request.getSession()+"wwwww");
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(loginUser));
    }
    /**
     * 通过username查找用户
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUser(@RequestParam String username) {
        ThrowUtils.throwIf(StringUtils.isBlank(username), ErrorCode.PARAMS_ERROR);
        List<User> user = userService.searchAll(username);
        return ResultUtils.success(user);
    }
    /**
     * 用户注销
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }


    /**
     * 删除用户
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest,
                                                   HttpServletRequest request) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResultUtils.success(userPage);
    }
    @PostMapping("/update/avatar")
    public BaseResponse<Boolean> updateUserAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(ObjectUtils.isEmpty(loginUser), ErrorCode.NOT_LOGIN_ERROR);

        boolean result = userService.updateUserAvatar(loginUser.getId(), file);
        return ResultUtils.success(result);
    }
    @PostMapping("/update/user")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(ObjectUtils.isEmpty(loginUser), ErrorCode.NOT_LOGIN_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest,user);
        return ResultUtils.success( userService.updateById(user));
    }
    @GetMapping("/count")
    public BaseResponse<Long> getUserCount(HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(ObjectUtils.isEmpty(loginUser), ErrorCode.NOT_LOGIN_ERROR);
        return ResultUtils.success(userService.count());
    }
}
